<template>
  <el-card class="box-card">
    <div class="header">
      <h2>
        文件下载列表
        <el-button type="success" plain @click="refresh" style="margin-left: 20px">刷新</el-button>
        <el-text class="mx-1" size="large" type="danger" style="margin-left: 20px">{{ dicPath }}</el-text>
      </h2>
    </div>
    <el-table :data="fileList" stripe style="width: 100%">
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="size" label="文件大小" />
      <el-table-column prop="date" label="上传时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <!-- 预览按钮 -->
          <!-- <el-button
            v-if="scope.row.fileType === 1 && isPreviewable(getFileSuffix(scope.row.name), scope.row.size)"
            type="success"
            size="small"
            @click="handlePreview(scope.row)"
            :icon="View"
          >
            预览
          </el-button> -->
          <el-button type="primary" size="small" @click="downloadFile(scope.row)">下载</el-button>
          <el-button type="success" size="small" @click="readFile(scope.row)">进入</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin-top: 20px">
      <el-col :span="6">
        <el-upload class="upload-demo" :action="actionUrl" :show-file-list="false" :on-success="handleSuccess">
          <el-button type="success">上传文件</el-button>
        </el-upload>
      </el-col>
      <el-col :span="6">
        <el-button type="success" @click="settingConfig">设 置</el-button>
      </el-col>
      <el-col :span="6">
        <div>{{ actionUrl }}</div>
      </el-col>
      <el-col :span="6"> </el-col>
    </el-row>
  </el-card>

  <!-- 文件预览模态框 -->
  <!-- <FilePreviewModal v-model="previewVisible" :file-id="currentPreviewFile?.id" @close="handlePreviewClose" /> -->
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View } from '@element-plus/icons-vue'
import { findFileList } from '../js/file'
import { baseHtpUrl } from '../js/baseUrl'
import { setBaseURL, getBaseURL } from '@/utils/request'
// import FilePreviewModal from './FilePreviewModal.vue'

const dicPath = ref("/")
const serverIp = ref("")
serverIp.value = getBaseURL()

const uploadUri = ref('/upload')
const actionUrl = ref(serverIp.value + uploadUri.value)

const fileList = ref([
  {
    name: 'jenkins.msi.sha256',
    size: '136 B',
    date: '2025-07-22 21:30',
    url: 'https://mirrors.tuna.tsinghua.edu.cn/jenkins/windows/2.520/jenkins.msi.sha256',
  },
])

// 预览相关状态
const previewVisible = ref(false)
const currentPreviewFile = ref(null)

const downloadFile = (file) => {
  let dic = dicPath.value + "/" + file.name
  window.open(serverIp.value + "/download?fileName=" + dic.substring(1, dic.length), '_blank')
}

const readFile = (file) => {

  if (file.fileType !== 2) {
    ElMessage({
      type: 'info',
      message: '请选择正确路径，再点击进入',
    })
    return
  }

  dicPath.value = "/" + file.name
  actionUrl.value = serverIp.value + uploadUri.value + "?dicPath=" + file.name
  console.log("actionUrl", actionUrl.value);
  findFileList({ "relativePathName": file.name, })
    .then((data) => {
      fileList.value = data.data
    })
    .catch((error) => {
      console.error(error)
    })
}

const handleSuccess = (response) => {
  ElMessage.success('上传成功')
}

const settingConfig = () => {
  ElMessageBox.prompt('请输入服务器IP和端口', '设置', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputValue: 'http://47.101.218.251:19321',
  })
    .then(({ value }) => {
      if (value.includes('http')) {
        serverIp.value = value
        actionUrl.value = value + uploadUri.value
      } else {
        serverIp.value = 'http://' + value
        actionUrl.value = 'http://' + value + uploadUri.value
      }

      setBaseURL(serverIp.value)
      // service.default.baseURL = serverIp.value
      ElMessage({
        type: 'success',
        message: `地址是:${actionUrl.value}`,
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}

const refresh = () => {
  // response
  findFileList(null)
    .then((data) => {
      fileList.value = data.data
      actionUrl.value = serverIp.value + uploadUri.value
    })
    .catch((error) => {
      console.error(error)
    })
}
// 获取文件后缀
const getFileSuffix = (fileName) => {
  if (!fileName) return ''
  const lastDotIndex = fileName.lastIndexOf('.')
  return lastDotIndex !== -1 ? fileName.substring(lastDotIndex) : ''
}

// 处理文件预览
const handlePreview = (file) => {
  // 为了兼容预览组件，需要转换数据格式
  currentPreviewFile.value = {
    id: file.name, // 使用文件名作为ID，实际项目中应该有真实的文件ID
    fileName: file.name,
    fileSize: parseFileSize(file.size),
    fileSuffix: getFileSuffix(file.name)
  }
  previewVisible.value = true
}

// 解析文件大小字符串为字节数
const parseFileSize = (sizeStr) => {
  if (!sizeStr) return 0

  const units = {
    'B': 1,
    'KB': 1024,
    'MB': 1024 * 1024,
    'GB': 1024 * 1024 * 1024,
    'TB': 1024 * 1024 * 1024 * 1024
  }

  const match = sizeStr.match(/^([\d.]+)\s*([A-Z]+)$/)
  if (match) {
    const value = parseFloat(match[1])
    const unit = match[2]
    return value * (units[unit] || 1)
  }

  return 0
}

// 关闭预览
const handlePreviewClose = () => {
  previewVisible.value = false
  currentPreviewFile.value = null
}

// 初始化加载文件列表
onMounted(() => {
  refresh()
})
</script>

<style scoped>
.box-card {
  max-width: 800px;
  margin-top: 30px;
}
</style>
